module.exports = (express, app) => {
  const path = require('path')
  const router = express.Router({
    mergeParams: true
  })

  // 获取全部数据
  router.get('/', async (req, res) => {
    const queryOptions = {}
    // 如果是Category 分类设置查找上级分类属性 
    if (req.Model.modelName === 'Category') {
      queryOptions.populate = 'parent'
    }
    await req.Model.find().setOptions(queryOptions).exec((err, data) => {
      // err && res.send({ code: 0, msg: err.message })
      if (err) {
        return res.send({ code: 0, msg: err.message })
      }
      res.send(data)
    })
  })

  // 根据id获取数据
  router.get('/:id', async (req, res) => {
    await req.Model.findById(req.params.id).exec((err, data) => {
      // err && res.send({ code: 0, msg: err.message })
      // res.send(data)
      if (err) {
        return res.send({ code: 0, msg: err.message })
      }
      res.send(data)
    })
  })

  /**
   * 添加
   * @param {String} name 
   */
  router.post('/', async (req, res) => {
    await req.Model.create(req.body, (err) => {
      err && res.send({ code: 0, msg: err.message })
      res.send({ code: 1 })
    })
  })


  /**
   * 删除
   * @param {String} id id字段
   */
  router.delete('/:id', async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id).exec((err, data) => {
      err && res.send({ code: 0, msg: err.message })
      res.send({ code: 1 })
    })
  })

  /**
   * 批量删除
   * @param {String} idArr 多个id使用,隔开
   */
  router.delete('/deleteMany/:idArr', async (req, res) => {
    const newIdArr = req.params.idArr.split(","); //格式化为我们需要的
    await req.Model.deleteMany({ _id: { $in: newIdArr } }).exec((err, data) => {
      err && res.send({ code: 0, msg: err.message })
      res.send({ code: 1 })
    })
  })

  /** 
   * 更新
   * @param {String} id id字段
   */
  router.put('/:id', async (req, res) => {
    await req.Model.findByIdAndUpdate(req.params.id, req.body).exec((err, data) => {
      err && res.send({ code: 0, msg: err.message })
      res.send({ code: 1 })
    })
  })

  app.use('/admin/api/rest/:resource', async (req, res, next) => {
    const modelName = require('inflection').classify(req.params.resource)
    req.Model = require(`../../models/${modelName}`)
    next()
  }, router)

  const multer = require('multer')
  const upload = multer({ dest: path.join(__dirname, '../../uploads') })

  app.post('/upload', upload.single('file'), async (req, res) => {
    const file = req.file
    file.url = 'http://127.0.0.1:3000/uploads/' + file.filename
    res.send(file)
  })
}